/*
 * @Description: 
 * @Autor: 万洲
 * @Date: 2022-11-21 14:44:40
 * @LastEditors: 万洲
 * @LastEditTime: 2022-11-21 15:19:01
 */
/*
 * @Description: 
 * @Autor: 万洲
 * @Date: 2021-12-04 14:12:05
 * @LastEditors: 万洲
 * @LastEditTime: 2022-11-14 11:15:31
 */

import axios, { AxiosInstance, CreateAxiosDefaults, InternalAxiosRequestConfig } from "axios";

export interface IListResponse<T> {
    code: number
    data: {
        current: number
        hitCount: boolean
        optimizeCountSql: boolean,
        orders: []
        pages: number,
        searchCount: boolean
        size: number
        total: number,
        records: T[]
    },
    msg: string,
    [key: string]: any
}
export type TApiResponse<T> = {
    code: number
    data: T,
    msg: string,
    [key: string]: any
}
export type TRequest<T> = Promise<TApiResponse<T>>
export type TApiListRequest<T> = Promise<IListResponse<T>>
/** 拦截器 */
export type TInterceptorHooks = {
    /** 请求开始拦截 */
    requestInterceptor?: (config: InternalAxiosRequestConfig<any>) => InternalAxiosRequestConfig<any>
    /** 请求失败拦截 */
    requestInterceptorCatch?: (error: any) => any
    responseInterceptor?: (response: any) => any
    responseInterceptorCatch?: (error: any) => any
}
// 拓展自定义请求配置
interface IExpandAxiosRequestConfig<D = any> extends CreateAxiosDefaults<any> {
    interceptorHooks?: TInterceptorHooks
    requestOptions?: InternalAxiosRequestConfig<any>
}
/**
* 参数处理
* @param {*} params  参数
*/
export function tansParams(params: any) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && value !== "" && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}
export default class HttpRequest {
    instance!: AxiosInstance
    constructor(createConfig: IExpandAxiosRequestConfig) {
        this.instance = axios.create({
            timeout: 30000,
            ...createConfig
        });
        this.initInterceptors(createConfig.interceptorHooks)
    }
    private initInterceptors(hooks?: TInterceptorHooks) {
        // 浙政钉小程序不支持可选运算符，这里默认给个空对象
        if (!hooks) hooks = {}
        this.instance.interceptors.request.use(hooks.requestInterceptor, hooks.requestInterceptorCatch)
        this.instance.interceptors.response.use(hooks.responseInterceptor, hooks.responseInterceptorCatch)
    }
    post<T>(url: string, params: T): any {
        return new Promise((resolve, reject) => {
            let result = this.instance.post(url, params);
            result
                .then((res) => {
                    return resolve(res.data);
                })
                .catch((err) => {
                    return reject(err.data);
                });
        });
    }
    put<T>(url: string, params: T): any {
        return new Promise((resolve, reject) => {
            let result = this.instance.put(url, params);
            result
                .then((res) => {
                    return resolve(res.data);
                })
                .catch((err) => {
                    return reject(err.data);
                });
        });
    }
    get<T>(url: string, params: T): any {
        return new Promise((resolve, reject) => {
            let result = this.instance.get(url, { params },);
            result
                .then((res) => {
                    return resolve(res.data);
                })
                .catch((err) => {
                    return reject(err.data);
                });
        });
    }

}


